package com.example.demo.api.service;

import com.example.demo.api.db.dao.TableUserDao;
import com.example.demo.api.db.dao.TbCityDao;
import com.example.demo.api.db.dao.TripDao;
import com.example.demo.api.db.pojo.TableUser;
import com.example.demo.api.db.pojo.TbCity;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

@Service
public class UserService {

    @Autowired
    private TableUserDao userDao;

    @Autowired
    private TripDao tripDao;

    @Autowired
    private TbCityDao cityDao;

    public long login(TableUser user){
        System.out.print("获取前");
        try{
            userDao.insert(user);
        }catch (Exception e){
            e.printStackTrace();
        }

        System.out.print("获取中：");
        Long id = userDao.searchUserId(user.getOpenId());
        System.out.print("获取后："+id+"" +"\n");
        return id;
    }

    public String searchUserLocation(String tel,String startDate,String endDate) throws Exception{
     //查询14天行程数据
        ArrayList<HashMap> list = tripDao.searchUserTrip(tel,startDate,endDate);
        String result = "低风险";
        out:for(HashMap map : list){
            String city = (String) map.get("city");
            String code = cityDao.searchCityCode(city); //城市编码
            String district = (String)map.get("district");
            String url = "http://m." + code + ".bendibao.com/news/yqdengji/?qu=" + district;
            org.jsoup.nodes.Document document = Jsoup.connect(url).get();
            org.jsoup.select.Elements elements = document.getElementsByClass("list-content");
            String temp = "低风险";
            Iterator iterator = elements.iterator();
            while (iterator.hasNext()){
                org.jsoup.nodes.Element one = (org.jsoup.nodes.Element)iterator.next();
                temp = one.select("p:last-child").text();
                if(temp.equals("高风险")) {
                    result = "高风险";
                    break out;
                }else if(temp.equals("中风险")){
                    result = "中风险";
                    break out;
                }
            }
        }
        return result;
    }


}
